package org.itboys.store.weixin;

import org.apache.ibatis.annotations.Param;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.solr.client.SolrClient;
import org.itboys.store.dto.ProductDTO;
import org.itboys.store.dto.ProductDetail;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.store.manager.OrderProductWeixinService;
import org.itboys.store.cache.BrandLoader;
import org.itboys.store.cache.ProductCategoryLoader;
import org.itboys.store.cache.ProductDetailLoader;
import org.itboys.store.constant.ProductConstant;
import org.itboys.store.dto.BrandCacheListDto;
import org.itboys.store.dto.CategoryCacheListDto;
import org.itboys.store.search.ProductSearchDoc;
import org.itboys.store.search.ProductSearchService;
import org.itboys.store.service.StoreProductCountService;
import org.itboys.store.service.StoreProductService;
import org.itboys.store.service.StoreProductTextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by huml on 2016/4/15.
 * 微信产品控制层
 */
@RestController
@RequestMapping("/store/weixin/product")
public class StoreProductWeixinController extends BaseController {
    @Autowired
    private OrderProductWeixinService orderProductWeixinService;
    @Autowired
    private StoreProductService productService;
    @Autowired
    private StoreProductTextService productTextService;
    @Autowired
    private StoreProductCountService storeProductCountService;
    @Autowired
    private ProductSearchService productSearchService;

    @Resource(name = "storeProductCategoryLoader")
    private ProductCategoryLoader productCategoryLoader;
    @Resource(name = "storeBrandLoader")
    private BrandLoader brandLoader;
    @Resource(name = "storeProductDetailLoader")
    private ProductDetailLoader productDetailLoader;
    @Resource(name = "storeProductSolrClient")
    private SolrClient productSolrClient;

    /**
     * 分类或品牌的页面
     * @param type  1表示分类   2表示品牌
     * @param model
     * @return
     */
    @RequestMapping("/productOrBrand")
    public ModelAndView productOrBrand(@RequestParam("type")Integer type,
                                       Model model){
        if(type.equals(1)){
            CategoryCacheListDto dto = productCategoryLoader.get(ProductConstant.CACHE_CATEGORY);
            model.addAttribute("categories", dto.getList());
        } else if (type.equals(2)) {
            BrandCacheListDto dto = brandLoader.get(ProductConstant.CACHE_BRAND);
            model.addAttribute("brands", dto.getList());
        }
        return new ModelAndView("");
    }

    /**
     * 产品的搜索
     * @param keyword
     * @param catId
     * @param brandId
     * @param model
     * @return
     */
    @RequestMapping("/productList")
    public ModelAndView productList(@RequestParam(value = "keyword", required = false) String keyword,
                                    @RequestParam(value = "catId", required = false) Long catId,
                                    @RequestParam(value = "brandId", required = false) Long brandId,
                                    @RequestParam(value = "sortField", required = false) String sortField,
                                    @RequestParam("type")Integer type,
                                    Model model){
        List<ProductDTO> dtos = orderProductWeixinService.list(catId, brandId, keyword, sortField, type, null, null);
        model.addAttribute("dtos", dtos);
        model.addAttribute("keyword", keyword);
        model.addAttribute("catId", catId);
        model.addAttribute("brandId", brandId);
        model.addAttribute("type", type);
        model.addAttribute("sortField", sortField);
        CategoryCacheListDto dto = productCategoryLoader.get(ProductConstant.CACHE_CATEGORY);//产品分类
        model.addAttribute("categories", dto.getList());
        return new ModelAndView("site/productList");
    }

    /**
     * 产品分页搜索
     * @param keyword
     * @param catId
     * @param brandId
     * @param sortField
     * @param pageNo
     * @param callback
     * @param response
     */
    @RequestMapping("/getProducts")
    public void getProducts(@RequestParam(value = "keyword", required = false) String keyword,
                            @RequestParam(value = "catId", required = false) Long catId,
                            @RequestParam(value = "brandId", required = false) Long brandId,
                            @RequestParam(value = "sortField", required = false) String sortField,
                            @RequestParam(value = "pageNo", required = false) Integer pageNo,
                            @RequestParam("type")Integer type,
                            @Param("callback")String callback,
                            HttpServletResponse response){
        try {
            List<ProductDTO> dtos = orderProductWeixinService.list(catId, brandId, keyword, sortField, type, pageNo, null);
            AjaxUtils.renderJsonporJson(response, callback, ResultPageDOHelper.getMsgResultDO(dtos, CommonConstants.SUCCESS));
        } catch (Exception e){
            logger.error("/store/weixin/product/getProducts error", e);
            AjaxUtils.renderJsonporJson(response, callback, ResultPageDOHelper.getErrorResultDO(-1, CommonConstants.FAIL));
        }
    }

    /**
     * 产品详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/productDetail")
    public ModelAndView productDetail(@RequestParam("id")Long id,
                                      Model model){
        ProductDetail detail = productDetailLoader.get(id);
        model.addAttribute("product", detail);
        //增加人气
        storeProductCountService.update(id, "readCount", detail.getReadCount()+1);
        productDetailLoader.clearCache(id);
        ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();//开启线程  往搜索引擎里加信息
        fixedThreadPool.execute(new Runnable(){
            @Override
            public void run() {
                try {
                    productSolrClient.deleteDocument(id.toString());
                    ProductDetail detail = productDetailLoader.get(id);
                    ProductSearchDoc doc = new ProductSearchDoc();
                    doc.setProductId(id);
//                    doc.setBrandId(detail.getBrandId());
//                    doc.setCategoryFullIdPath(detail.getCatId().toString());
                    doc.setProductName(detail.getTitle() + ":::" + detail.getBrandName() + ":::" + detail.getCatName());
                    doc.setPrice(detail.getRealPrice());
                    doc.setSoldCount(detail.getSoldCount());
                    doc.setReadCount(detail.getReadCount());
                    doc.setType(detail.getType());
                    productSearchService.buildProductSearchIndex(doc);
                } catch (Exception e) {
                    logger.error("publishSupplyPush error", e);
                }
            }
        });
        return new ModelAndView("site/productDetail1");
    }

}
